﻿using Mapster;
using System.Reflection;

namespace Photo.Core.Extensions
{
    /// <summary>
    /// 映射器扩展方法
    /// </summary>
    public static class AdaptExtension
    {
        /// <summary>
        /// 映射器扩展方法-将input中带有AdaptMemberAttribute标识的字段自动转换赋值至实体对象中
        /// </summary>
        /// <typeparam name="T_input"></typeparam>
        /// <typeparam name="T_entity"></typeparam>
        /// <param name="input"></param>
        /// <param name="entity"></param>
        public static void AdaptTo<T_input, T_entity>(this T_input input, ref T_entity entity)
        {
            foreach (PropertyInfo p in typeof(T_input).GetProperties())//遍历入参，判断入参中是否包含AdaptMemberAttribute头缀，包含即赋值
            {
                var adaptMemberAttribute = System.Attribute.GetCustomAttribute(p, typeof(AdaptMemberAttribute)) as AdaptMemberAttribute;
                if (adaptMemberAttribute != null)//判断是否具有AdaptMemberAttribute
                {
                    //实体类所对应的属性
                    var entityValue = typeof(T_entity).GetProperty(p.Name).GetValue(entity);
                    var inputValue = p.GetValue(input);
                    if (inputValue != entityValue)
                    {
                        typeof(T_entity).GetProperty(p.Name).SetValue(entity, inputValue);
                    }
                }
            }
        }
    }
}
